package com.micro.magupe.auth.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.micro.magupe.auth.entity.Menu;
import com.micro.magupe.auth.service.MenuService;
import com.micro.magupe.common.annotation.Log;
import com.micro.magupe.common.bean.Result;
import com.micro.magupe.common.bean.Tree;
import com.micro.magupe.common.vo.MenuVO;

@RequestMapping("/menu")
@Controller
public class MenuController {

	@Autowired
	MenuService menuService;
	
	@ResponseBody
	@RequestMapping(value="/getById", method=RequestMethod.GET)
	MenuVO getById(@RequestParam String id) throws IllegalAccessException, InvocationTargetException {
		MenuVO menuVO = menuService.getById(id);
		return menuVO;
	}
	
	@PreAuthorize("hasRole('ROLE_menu:list')")
	@RequestMapping("/list")
	@ResponseBody
	List<MenuVO> list(@RequestParam Map<String, Object> params) {
		List<MenuVO> menus = menuService.listQuery(params);
		
		for (MenuVO menuVO : menus) {
			menuVO.setParentId(menuVO.getParent().getId());
		}
		
		return menus;
	}
	
	@PostMapping("/save")
	@ResponseBody
	Result save(MenuVO menuVO) {
		if (menuService.save(menuVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	@PostMapping("/update")
	@ResponseBody
	Result update(MenuVO menuVO) {
		if (menuService.update(menuVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	/**
	 * @PreAuthorize 注解适合进入方法前的权限验证， @PreAuthorize可以将登录用户的roles/permissions参数传到方法中。
	 * @PostAuthorize 注解使用并不多，在方法执行后再进行权限验证。
	 * @return
	 */
	@Log("首页获取所有菜单")
	@PreAuthorize("hasRole('ROLE_menu:list')")
	@RequestMapping("/listAll")
	@ResponseBody
	List<MenuVO> listAll() {
		List<MenuVO> menus = menuService.list(new Menu("0"));
		
		for (MenuVO menuVO : menus) {
			menuVO.setParentId(menuVO.getParent().getId());
		}
		
		return menus;
	}
	
	@ResponseBody
	@RequestMapping(value="/listByRoleId", method=RequestMethod.GET)
	List<MenuVO> listByRoleId(@RequestParam String id) {
		return menuService.listByRoleId(id);
	}
	
	@GetMapping("/tree")
	@ResponseBody
	Tree<MenuVO> tree() {
		Tree<MenuVO>  tree = menuService.getTree();
		return tree;
	}

	@GetMapping("/tree/{roleId}")
	@ResponseBody
	Tree<MenuVO> tree(@PathVariable("roleId") String roleId) {
		Tree<MenuVO> tree = menuService.getTree(roleId);
		return tree;
	}
}
